/*
 * @Author: evan.wan
 * @Date:   2016-06-25 15:55:20
 */

'use strict';
define([
    '../../../common/service',
    'text!../tpl/allFontAndDesignElement.html',
    'text!../tpl/eachDesignElement.html'
], function(
    http,
    tpl,
    eachAttachTmpl
) {
    function me() {
        var self = this;
        this.init = function(callback) {
            self.callback = callback;
            self.param = {
                pSize : 160,
                cPage : 1
            };
            self.$root = $('#tab-content2');
            self.render();
        }

        this.render = function() {
            self.$root.html(I18N.parse(tpl, 'elementList'));
            self.event();
            $(window).resize(function() {
                self.adjuestElementGroup();
            });
        }

        this.event = function() {
            //加载模板的 设计元素
            self.getDesignElements(self.param);
            //上传设计元素
            self.$root.find('#addDesignElement').off('click').on('click', function(){$('#uploadFile').trigger('click');});
            $('#uploadFile').change(function() {
                self.uploadFile();
            })
        }

        /**
         * 上传设计元素
         */
        this.uploadFile = function(e) {
            var formData = new FormData($('#uploadFileForm')[0]);
            $.ajax({
                url: apiUrl + "/ecelement/uploadDesignEleAll", //server script to process data
                type: 'POST',
                cache: false,
                contentType: false,
                processData: false,
                success: function(result) {
                    self.getDesignElements(self.param);
                },
                error: function(result) {
                    console.info(result);
                },
                data: formData,
                xhrFields: {
                    withCredentials: true
                }
            });
        }

        this.getDesignElements = function(param){
            Kit.loading.show(self.$root);
            http.work('/ecelement/getAllDesignEle', param, 'POST').then(function(res) {
                if (res.succeed){
                    var elementGroup = _.groupBy(res.data, function(o) {
                        return o.attachElementType
                    });
                    var elementGroupArr = [];
                    var allDesignEleType = [];        //所有查出来的设计元素类型
                    for (var q in elementGroup) {
                        allDesignEleType.push(q);
                        elementGroupArr.push({
                            type: q,
                            list: elementGroup[q]
                        });
                    }
                    if($.inArray('1', allDesignEleType) == -1) {
                        elementGroupArr.push({type:1, list: null});
                    }
                    if($.inArray('2', allDesignEleType) == -1) {
                        elementGroupArr.push({type:2, list: null});
                    }
                    if($.inArray('3', allDesignEleType) == -1) {
                        elementGroupArr.push({type:3, list: null});
                    }
                    var elementGroupArrT = _.sortBy(elementGroupArr, function(item) {
                        return item.type;
                    });
                    var container = self.$root.find('.design-ele-container');
                    container.empty();
                    _.each(elementGroupArrT, function(el) {
                        container.append(_.template(I18N.parse(eachAttachTmpl, 'elementList'))({
                            d: el
                        }));
                        if(el.list)
                            self.renderPage(el.type, param.cPage, param.pSize, el.list.length);
                    });
                    self.$root.find('.each-attach-unfold').off('click').on('click', $.proxy(self.findThisTypeAllElement, self));
                    self.$root.find('li.unActive').hide();
                    self.adjuestElementGroup();
                    $(window).resize(function() {
                        self.adjuestElementGroup();
                    });
                }
                Kit.loading.hide(self.$root);
            });
        }


        /**
         * 单类型 分页请求
         */
        this.getDesignElementsEach = function(who, param){
            Kit.loading.show(who);
            http.work('/ecelement/getAllDesignElePage', param, 'POST').then(function(res) {
                if (res.succeed){
                    who.empty();
                    _.each(res.data.attaches, function(el) {
                        who.append('<li><div class="each-attach-img-div"><img src="' + el.attachElementImg + '" /></div></li>');
                    });
                    self.adjuestElementGroup();
                }
                Kit.loading.hide(who);
            });
        }

        /**
         * 渲染分页
         */
        this.renderPage = function(type, _currentPage, _perPage, _totalSize) {
            var pagerE = $("div[data-id='" + type + "']", self.$root);
            pagerE.empty();
            if (!_totalSize || _totalSize == 0){
                return;
            }
            pagerE.page({
                type: 1, //1 普通，2 带显示条数，3，简洁紧凑格式的菜单
                totalItems: _totalSize, //总共有n条数据
                perPage: _perPage, //每页默认显示10条
                currentPage: _currentPage,
                perPages: [5, 10, 20, 50]
            }).off("PAGE_CHANGE").on("PAGE_CHANGE", function(e) { //页数点击 事件
                console.log(e.originalEvent.data); //{currentPage: 第几页 int} currentPage: 1
                var current = $(e.currentTarget);
                self.param.cPage = e.originalEvent.data.currentPage;
                self.param.type = current.data('id');
                self.getDesignElementsEach(current.parent().prev().find('ul'), self.param);
            }).off("SHOW_ITEMS_CHANGE").on("SHOW_ITEMS_CHANGE", function(e) { //页数点击 事件
                console.log(e.originalEvent.data); //{currentPage: 第几页 int}  {currentPage: 1, perpage: 50}
                var currentt = $(e.currentTarget);
                self.param.cPage = e.originalEvent.data.currentPage;
                self.param.pSize = e.originalEvent.data.perpage;
                self.param.type = currentt.data('id');
                self.getDesignElementsEach(current.parent().prev().find('ul'), self.param);
            });
            if(_totalSize <= _perPage){
                //总共只有一页
                pagerE.find('.page-item:last').addClass("disabled");
            }
        }

        /**
         * 展开此种类元素
         */
        this.findThisTypeAllElement = function(e) {
            var $swap = $(e.currentTarget);
            var fold = I18N.getText('elementList', 'expandAll') + '&nbsp;&nbsp;<i class="glyphicon glyphicon-menu-down"></i>';
            var unfold = I18N.getText('elementList', 'shrinkAll') + '&nbsp;&nbsp;<i class="glyphicon glyphicon-menu-up"></i>';
            var t = $swap.hasClass('unfold') ? fold : unfold;
            var $lis = $swap.prev().prev().find('ul li.unActive');
            $swap.html(t);
            $swap.hasClass('unfold') ? $lis.slideUp(200) : $lis.slideDown(200);
            $swap.toggleClass('unfold');
            // self.adjuestElementGroup();
        }

        /**
         * 调整元素中图片的显示数量
         */
        this.adjuestElementGroup = function(e) {
            self.$root.find('.each-attach').each(function() {
                var $container = $(this).find('.each-attach-img');
                var $unfold = $(this).find('.each-attach-unfold');
                var unfoldFlag = $unfold.hasClass('unfold');
                var w = $(this).width(); //包含图片的容器宽度
                var n = Math.floor(w / 150) * 2; //显示两行的数量
                $container.find('ul li').each(function(i, v) {
                    $(this).toggleClass('unActive', i >= n);
                    if (!unfoldFlag) {
                        $(this).hasClass('unActive') ? $(this).hide() : $(this).show();
                    }
                });
            });


            self.$root.find('.each-attach-img').each(function() {
                var width = $(this).width() - 1; //外面容器的宽度.
                var n = Math.floor(width / 150); //显示1行的数量
                var w = 150 * n; //每个元素84px
                var marginRight = (width - w) / (n - 1); //margin-right的值,最后一个为0;
                $(this).find('ul li').css('margin-right', marginRight + 'px');
                $(this).find('ul li:nth-child(' + n + 'n)').css('margin-right', '0px');
            })


        }


    }
    return new me();
});